#include <sys/select.h>
#include <iostream>
#include "Socket.hpp"

class SelectServer
{
public:
    void Init()
    {
        _listenSock.Sock();
        _listenSock.Bind(9999);
        _listenSock.Listen();
    }

    void Run()
    {
        int listenfd = _listenSock.Fd();
        while(true)
        {
            fd_set read_fds;
            FD_ZERO(&read_fds);
            FD_SET(listenfd, &read_fds);
            timeval time; bzero(&time, sizeof(time));
            time.tv_sec = 2;
            time.tv_usec = 0;
            /*
            After select() has returned, *fds will be cleared of all file descriptors except for those that are ready
            for reading.
            */
            int ret = select(listenfd + 1, &read_fds, nullptr, nullptr, &time);
            if(ret == 0) {
                std::cerr << "time out" << std::endl;
            }
            else if(ret < 0) {
                std::cerr << "select err" << std::endl;
            }
            else {
                std::cerr << "get new links" << std::endl;
            }
        }
    }

private:
    Socket _listenSock;
};